package db

import (
	"fmt"
	"log"
	"os"
	"sync"
	"time"

	"gitee.com/satyr/tools/conf"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var mysqlDriver *gorm.DB
var once sync.Once

func DB() *gorm.DB {
	return mysqlDriver
}

func Init(conf conf.Db) (err error) {
	exitCode := -1
	once.Do(func() {
		//dsn := "root:CBd123!@#99.@tcp(10.69.66.35:8091)/oasis_kmr_kejie?charset=utf8mb4&parseTime=True&loc=Local"
		dsn := getDsn(conf)
		mysqlDriver, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
			Logger: logger.New(
				log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer（日志输出的目标，前缀和日志包含的内容——译者注）
				logger.Config{
					SlowThreshold:             time.Second, // 慢 SQL 阈值
					LogLevel:                  logger.Info, // 日志级别
					IgnoreRecordNotFoundError: true,        // 忽略ErrRecordNotFound（记录未找到）错误
					Colorful:                  true,        // 彩色打印
				},
			),
		})
		if err != nil {
			fmt.Println(fmt.Errorf("出错了: %+v", err))
			os.Exit(exitCode)
		}
	})
	return err
}

// 获取dsn链接地址
func getDsn(c conf.Db) (dsn string) {
	dsn = fmt.Sprintf("%s:%s@%s(%s:%s)/%s%s",
		c.Username, c.Password, c.Protocol,
		c.Address, c.Port, c.Dbname, c.Params,
	)
	return
}
